package com.rds.benchmark.connector;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.util.HashSet;
import java.util.Set;

public class SentinelJedisConnector implements JedisConnector {

    private static JedisSentinelPool pool;

    private String stringDes;

    public SentinelJedisConnector(final String host, final int port, final int max_threads, final String sentinelPassword, final String masterName, final String password) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(max_threads + 1);
        poolConfig.setMaxIdle(max_threads + 1);

        Set<String> hostAndPortsSet = new HashSet<>();
        // 添加节点
        hostAndPortsSet.add(host + ":" + port);

        pool = new JedisSentinelPool(masterName,
                hostAndPortsSet, poolConfig, TIME_OUT, TIME_OUT, password,
                0, null, TIME_OUT, TIME_OUT, sentinelPassword, null);

        stringDes = "SentinelJedisConnector(host='" + host + "', port='"+ port +"', masterName='" + masterName + "' )";
        System.out.println(stringDes + " connecting....");
    }


    @Override
    public Jedis getJedis() {
        return pool.getResource();
    }

    @Override
    public boolean test() {
        try(Jedis jedis = pool.getResource()) {
            return "PONG".equalsIgnoreCase(jedis.ping());
        }
    }

    @Override
    public String type() {
        return "SENTINEL";
    }

    @Override
    public String toString() {
        return stringDes;
    }
}
